package com.yml.mybatis.gererator.util;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

/**
 * @author YML
 * @since 2023-07-21 11:48
 */
public class FreemarkerUtils {

    private static final String templatePath = "template";

    private static  Configuration configuration = null;

    static {
        configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
        configuration.setClassForTemplateLoading(FreemarkerUtils.class, "/");
    }

    public static void createFileFromTemplate(Path path, Map<String, Object> dataMap,String templateFile) throws Exception {
        Template template = configuration.getTemplate(templatePath + "/" + templateFile);
        if (!Files.exists(path.getParent())) {
            Files.createDirectories(path.getParent());
        }
        Files.deleteIfExists(path);
        File target = new File(path.toUri());
        if (target.exists()){
            throw new RuntimeException(path.toUri() + " 文件已存在");
        }
        try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target)))) {
            template.process(dataMap, out);
        }
    }

    public static String createStringFromTemplate(Map<String, Object> dataMap,String templateFile) throws Exception {
        Template template = configuration.getTemplate(templatePath + "/" + templateFile);
        try (Writer out = new StringWriter()){
            template.process(dataMap, out);
            return out.toString();
        }
    }
}
